package com.fanhang.samples.spring.security.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Service;

import com.fanhang.samples.spring.security.common.SampleUserDetails;
import com.fanhang.samples.spring.security.dao.UserDao;
import com.fanhang.samples.spring.security.po.User;
import com.fanhang.samples.spring.security.service.SessionService;
import com.fanhang.samples.spring.security.service.UserService;

@Service
public class SessionServiceImpl implements SessionService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private UserDao userMapper;
	
	@Autowired
	private SessionRegistry sessionRegistry;
	
	@Autowired
	private UserService userService;
	
	private SampleUserDetails getUserDetails() {
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if (auth == null) {
			return null;
		}
		Object object = auth.getPrincipal();
		if (object instanceof SampleUserDetails) {
			return (SampleUserDetails) object;
		}
		if ("anonymousUser".equals(object)) {
			logger.warn("anonymousUser");
			User anonymousUser = userService.getByName("anonymousUser");
			if (anonymousUser != null) {
				SampleUserDetails userDetails = new SampleUserDetails(anonymousUser);
				return userDetails;
			}
		}
		return null;
	}
	
	public User getUser() throws SessionAuthenticationException {
		SampleUserDetails userDetails = getUserDetails();
		if (userDetails != null) {
			return userDetails.getUser();
		}
		throw new SessionAuthenticationException("UserDetails not found");
	}

	@Override
	public void getList() {
		List<Object> list = sessionRegistry.getAllPrincipals();
		for (Object object : list) {
			System.out.println(object);
		}
	}

	@Override
	public void get(String sessionId) {
		
	}

	@Override
	public void delete(String sessionId) {
		
	}
}
